{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

<div id="weatherhistorychart" v-cloak>
  <div class="card mb-3 border-nmd-0 m-n2 m-md-0" v-if="show">
    <div class="card-body p-md-3 p-0 mt-3 mt-md-0">
      <div class="row">
        <div class="col-12">
          <div class="row d-inline m-0 justify-content-center align-items-stretch">
            <apexchart
              ref="weather_history_line_chart"
              id="weather_history_line_chart"
              height=240
              type="line"
              :options="options"
              :series="series"></apexchart>
          </div>
          <div class="small text-muted text-right">timezone: ${ timezone }</div>
        </div>
      </div>
    </div>
  </div>
  <div class="card mb-3 border-nmd-0 m-n2 m-md-0" v-if="!show" style="min-height: 255px;">
      <div class="text-center chart-spiner-placeholder">
        <b-spinner label="Loading..." variant="secondary"></b-spinner>
      </div>
  </div>
</div>

<style>
#weatherhistorychart {
  min-width: 50%;
  margin: 0 .5rem; 
}

.apexcharts-toolbar-custom-icon {
  height: 24px;
  width: 30px;
}
</style>

<script>
(function() {
  // The global window.Apex variable below can be used to set common options for all charts on the page
  Apex = {
    dataLabels: {
      enabled: false
    },
    tooltip: {
      followCursor: false,
      theme: 'dark',
      x: {
        show: false
      },
      marker: {
        show: false
      },
    },
    grid: {
      clipMarkers: false
    },
  }
  var chartDegreeUnit = '°F'
  var myChart = new Vue({
    delimiters: ['${', '}'],
    el: '#weatherhistorychart',
    components: {
      apexchart: VueApexCharts,
    },
    data: function() {
      return {
        timezone: '',
        show: true,
        options: {
          chart: {
            id: 'weather-history-chart',
            toolbar: {
              tools: {
                download: false,
                selection: false,
                zoom: false,
                zoomin: false,
                zoomout: false,
                reset: false,
                pan: false,
                customIcons: [
                  {
                    icon: '<i>&#8451;</i>',
                    title: 'Display as Celsius',
                    class: '',
                    click: function(e) {
                      console.log('Display as Celsius', myChart.series[0].data);
                      chartDegreeUnit = '°C';
                      myChart.series[0].data = myChart.series[0].data_c;
                    },
                    appendTo: 'left'
                  },
                  {
                    icon: '<i>&#8457;</i>',
                    title: 'Display as Fahrenheit',
                    class: '',
                    click: function(e) {
                      console.log('Display as Fahrenheit', myChart.series[0].data);
                      chartDegreeUnit = '°F';
                      myChart.series[0].data = myChart.series[0].data_f;
                    },
                    appendTo: 'left'
                  },
                  {
                    icon: '<i class="fa fa-download"></i>',
                    title: 'Download as csv',
                    class: '',
                    click: function(e) {
                      myChart.downloadAllData()
                    }
                  },
                ]
              },
            },
          },
          xaxis: {
            type: 'datetime',
            labels: {},
          },
          yaxis: {
            labels: {
              formatter: function(value) {
                return value.toFixed(1) + chartDegreeUnit
              }
            },
          },
          tooltip: {
            x: {
              format: 'dd MMM yyyy HH:mm'
            }
          }
        },
        series: [{
          name: "Temperature",
          data: [],
          data_c: [],
          data_f: []
        }],
      }
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        this.refresh();
      },
      clear() {
        console.log('Clear charts.');
        // this.series.data.splice(0);
      },
      refresh() {
        this.fetchData();
      },
      getUrlArgs() {
        // placeholder to add custom parameters
        {% if site %}
        return '?site={{ site.entity_id }}';
        {% else %}
        return '';
        {% endif %}
      },
      fetchData() {
        url = '{% url 'core:weather_data_json' weather_station_id %}' + this.getUrlArgs();
        console.log('Fetching weather chart from ', url);
        axios.get(url).then(response => {
          console.log('Fetching weather chart got ', response.data.values);
          this.timezone = response.data.tz || 'UTC';
          if (response.data.values.length < 20) {
            this.$refs['weather_history_line_chart'].updateOptions({markers: {size: 5}});
          } else {
            this.$refs['weather_history_line_chart'].updateOptions({markers: {size: 2}});
          }
          if (response.data.values.length == 0) {
            this.series[0].data = [{y:0, x:new Date().getTime()}]
          } else {
            this.series[0].data = response.data.values.map(x => { return { y: x.temp_f, x: parse_date(x.datetime).getTime() } } );
            this.series[0].data_c = response.data.values.map(x => { return { y: x.temp_c, x: parse_date(x.datetime).getTime() } } );
            this.series[0].data_f = response.data.values.map(x => { return { y: x.temp_f, x: parse_date(x.datetime).getTime() } } );
          }
          });
      },

      downloadAllData: function() {
          url = '{% url 'core:weather_data_json' weather_station_id %}'
          if (this.getUrlArgs() && this.getUrlArgs().length > 0) {
              url += this.getUrlArgs() + "&";
          } else {
              url += '?';
          }
          url += 'range=all&unit=';
          if (chartDegreeUnit == '°F') {
              url += "f";
          } else {
              url += "c";
          }
          console.log('Fetching all weather data from ', url);
          this.show = false;
          axios.get(url).then(response => {
              let lines = [];
              lines.push('Date/Time,Temperature (' + chartDegreeUnit + ')');

              if (response.data.values) {
                console.log('Fetching weather chart got ', response.data.values.length);
                for (let i = 0; i < response.data.values.length; i++) {
                  let date = new Date(response.data.values[i].datetime).toLocaleString()
                  lines.push(['"', date, '"', ',', response.data.values[i].temp].join(''));
                }
              }
              saveTextAsCsvFile('Weather History.csv', lines.join('\n'));
              this.show = true;
          })
          .catch(err => {
            console.error('Fetching all weather data error :', err)
            this.show = true;
          });
      },
    }
  })
})();

</script>
